<template>
  <CustomTableCard 
    footer
    temporary 
    actions 
    :total="total" 
    :page.sync="queryParams.page" 
    :limit.sync="queryParams.limit" 
    :width="1000"
    :showDrawer.sync="showDrawer" 
    @on-page="getList" 
    @cancel="handleCancel"
    @ok="handleOk"
    :title="baseInfo.id ? $t('actions.edit') : $t('actions.add')">
    <v-container fluid class="py-0">
      <v-row no-gutters>
        <v-col cols="2" xs="4" style="border-right: 1px solid #ccc;">
          <div class="mb-2 mr-2 mt-2 text-h6 d-flex justify-space-between">
            <label>组织架构</label>
            <v-btn @click="clearDept" small color="info">查看全部员工</v-btn>
          </div>
          <el-tree
            :data="deptList"
            node-key="id"
            :expand-on-click-node="false"
            default-expand-all
            @node-click="handleClickNode"
            :props="{
              children: 'childs',
              label: 'name'
            }">
          </el-tree>
        </v-col>
        <v-col cols="10" xs="6">
          <v-row class="mb-4 pl-4">
            <v-col cols="3">
              <v-text-field
                v-model.trim="queryParams.keyword"
                :label="$t('placeholder.keyword')"
                outlined
                dense
                hide-details
                clearable
                @keyup.enter.native="getList(1)"
              ></v-text-field>
            </v-col>
            <v-col>
              <v-btn color="info" class="mr-3" @click="getList(1)">{{ $t('actions.search') }}</v-btn>
            </v-col>
            <v-col cols="1" class="text-right mr-3">
              <v-btn color="primary" @click="showDrawer = true">{{ $t('actions.add') }}</v-btn>
            </v-col>
          </v-row>
          <el-table
            v-loading="listLoading"
            v-auto-height
            :height="tableHeight"
            :data="tableData"
            stripe
            fit
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection"
              align="center"
              width="55">
            </el-table-column>
            <el-table-column
              prop="username"
              :label="$t('organization.userModules.field.username')"
              fixed="left"
              width="120">
            </el-table-column>
            <el-table-column
              prop="name"
              :label="$t('organization.userModules.field.name')"
              fixed="left"
              width="120">
            </el-table-column>
            <el-table-column
              prop="name_en"
              :label="$t('organization.userModules.field.nameEn')"
              width="120">
            </el-table-column>
            <el-table-column
              :label="$t('organization.userModules.field.nationality')"
              width="120">
              <template slot-scope="scope">
                <span>{{scope.row.nationality && scope.row.nationality.name}}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              :label="$t('organization.userModules.field.deptname')"
              width="200">
              <template slot-scope="scope">
                <span>{{scope.row.department && scope.row.department.name}}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('organization.userModules.field.role')"
              width="160">
              <template slot-scope="scope">
                <v-chip v-for="item in scope.row.roles" :key="item.id" small label>{{item.name}}</v-chip>
              </template>
            </el-table-column>
            <el-table-column
              prop="phone"
              :label="$t('organization.userModules.field.phone')"
              width="120">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="remark"
              width="180"
              :label="$t('organization.userModules.field.remark')">
            </el-table-column>
            <el-table-column
              prop="created_at"
              :label="$t('organization.userModules.field.createTime')"
              width="160">
            </el-table-column>
            <el-table-column
              fixed="right"
              prop="status"
              :label="$t('organization.userModules.field.status')"
              width="140">
              <template slot-scope="{ row }">
                <v-switch class="mt-0" dense hide-details :input-value="row.status == 1" :label="row.status == 1 ? '已激活' : '已锁定'" @change="setStatus(row)"></v-switch>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              :label="$t('organization.userModules.field.action')"
              align="center"
              width="140">
              <template slot-scope="{ row }">
                <v-btn class="mr-2" small color="primary" outlined @click="handleEdit(row)">{{ $t('actions.edit') }}</v-btn>
                <v-btn small color="info" outlined @click="handleTransfer(row)">{{ $t('actions.transfer') }}</v-btn>
              </template>
            </el-table-column>
          </el-table>
        </v-col>
      </v-row>
    </v-container>
    <div slot="actions" style="padding-left: 300px;">
      <v-btn small color="info" :disabled="!multipleSelection.length" class="mr-2" @click="handleTransfer()">{{ $t('actions.transfer') }}</v-btn>
      <v-btn small color="success" :disabled="!multipleSelection.length" class="mr-2" @click="setStatusAll(1)">{{ $t('actions.open') }}</v-btn>
      <v-btn small color="warning" :disabled="!multipleSelection.length" @click="setStatusAll(2)">{{ $t('actions.close') }}</v-btn>
    </div>
    <section slot="drawer" class="pa-3">
      <v-form
        ref="form"
        :lazy-validation="false"
      >
        <v-card class="mb-4">
          <v-card-text>
            <div class="d-flex pt-2">
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('organization.userModules.field.username') }}</label>
                <v-text-field
                  v-model="baseInfo.username"
                  placeholder="请输入"
                  clearable
                  dense
                  :rules="[rules.required]"
                  required
                ></v-text-field>
              </div>
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3"><small v-if="!baseInfo.id" class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('organization.userModules.field.password') }}</label>
                <template v-if="baseInfo.id">
                  <v-text-field
                    v-model="baseInfo.password"
                    placeholder="请输入"
                    clearable
                    dense
                  ></v-text-field>
                </template>
                <template v-else>
                  <v-text-field
                    v-model="baseInfo.password"
                    placeholder="请输入"
                    clearable
                    dense
                    :rules="[rules.required]"
                    required
                  ></v-text-field>
                </template>
              </div>
            </div>
            <div class="d-flex pt-2">
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('organization.userModules.field.name') }}</label>
                <v-text-field
                  v-model="baseInfo.name"
                  placeholder="请输入"
                  clearable
                  dense
                  :rules="[rules.required]"
                  required
                ></v-text-field>
              </div>
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3">{{ $t('organization.userModules.field.nameEn') }}</label>
                <v-text-field
                  v-model="baseInfo.name_en"
                  placeholder="请输入"
                  clearable
                  dense
                ></v-text-field>
              </div>
            </div>
            <div class="d-flex pt-2">
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3">{{ $t('organization.userModules.field.email') }}</label>
                <v-text-field
                  v-model="baseInfo.email"
                  placeholder="请输入"
                  clearable
                  dense
                ></v-text-field>
              </div>
              <div class="d-flex align-center flex-grow-1 px-3">
                <label style="width: 140px" class="text-right pr-3">{{ $t('organization.userModules.field.phone') }}</label>
                <v-text-field
                  v-model="baseInfo.phone"
                  placeholder="请输入"
                  clearable
                  dense
                ></v-text-field>
              </div>
            </div>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3">{{ $t('organization.userModules.field.deptname') }}</label>
              <v-menu
                v-model="openMenu"
                :close-on-content-click="false"
                :nudge-width="200"
                :max-width="500"
              >
                <template v-slot:activator="{ on, attrs }">
                  <v-text-field
                    v-model="parentname"
                    placeholder="请输入"
                    dense
                    readonly
                    v-bind="attrs"
                    v-on="on"
                  ></v-text-field>
                </template>
                <v-card>
                  <v-card-text>
                    <v-text-field
                      v-model="filterText"
                      label="输入关键字进行过滤"
                      flat
                      hide-details
                      outlined
                      clearable
                      dense
                      clear-icon="mdi-close-circle-outline"
                      class="mb-2"
                    ></v-text-field>
                    <el-tree
                      :data="deptList"
                      :props="{
                        children: 'childs',
                        label: 'name'
                      }"
                      default-expand-all
                      :highlight-current="true"
                      :expand-on-click-node="false"
                      :filter-node-method="filterNode"
                      @node-click="handleSelectionDept"
                      ref="tree">
                    </el-tree>
                  </v-card-text>
                </v-card>
              </v-menu>
            </div>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3">{{ $t('organization.userModules.field.role') }}</label>
              <v-select
                v-model="baseInfo.role_id"
                :items="roleList"
                item-value="id"
                item-text="name"
                multiple
                chips
                deletable-chips
                dense
                hide-details
              >
              </v-select>
            </div>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3">{{ $t('organization.userModules.field.remark') }}</label>
              <v-text-field
                v-model="baseInfo.remark"
                placeholder="请输入"
                clearable
              ></v-text-field>
            </div>
          </v-card-text>
        </v-card>
      </v-form>
    </section>
    <transfer :show.sync="transfer.show" :ids="transfer.ids" @success="getList"/>
  </CustomTableCard>
</template>

<script>
import { mapState } from 'vuex'
import { getUserList, setStatus, createUser, updateUser } from '@/api/organization'
import mixin from './mixin'
import transfer from './components/transfer'

export default {
  name: 'user',
  mixins: [mixin],
  components: {
    transfer
  },
  created() {
    if (!this.deptList.length) {
      this.$store.dispatch('organization/getDeptList', {page: 1, limit: 500})
    }
    if (!this.roleList.length) {
      this.$store.dispatch('organization/getRoleList', {page: 1, limit: 1000})
    }
    this.getList()
    this.cloneFormData()
  },
  activated() {
    console.log('activated')
    this.getList()
  },
  deactivated() {
    console.log('deactivated')
  },
  computed: {
    ...mapState('organization', ['deptList', 'roleList'])
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      tableHeight: 500,
      showDrawer: false,
      openMenu: false,
      tableData: [{}],
      total: 0,
      listLoading: false,
      queryParams: {
        page: 1,
        limit: 20,
        keyword: '',
        department_id: undefined
      },

      baseInfo: {
        id: undefined,
        name: '',
        name_en: '',
        username: '',
        email: '',
        phone: '',
        nationality_id: undefined,
        department_id: undefined,
        role_id: [],
        password: '',
        remark: ''
      },

      filterText: '',
      parentname: '',

      multipleSelection: [],

      transfer: {
        show: false,
        ids: []
      },

      rules: {
        required: value => !!value || 'required',
      }
    }
  },

  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.name ? data.name.indexOf(value) !== -1 : data.title.indexOf(value) !== -1;
    },
    clearDept() {
      this.queryParams.department_id = undefined
      this.deptName = '全部'
      this.getList()
    },
    handleSelectionDept(data) {
      this.baseInfo.department_id = data.id
      this.parentname = data.name
      this.openMenu = false
    },
    handleClickNode(data) {
      this.queryParams.department_id = data.id
      this.deptName = data.name
      this.getList()
    },
    // 克隆数据 用于重置数据使用
    cloneFormData() {
      this._baseInfo = Object.assign({}, this.baseInfo)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取列表
    getList(page) {
      if (/\d+/.test(page)) {
        this.queryParams.page = page
      }
      this.listLoading = true
      getUserList(this.queryParams).then(response => {
        this.tableData = response.data.data
        this.total = response.data.count
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 转移部门
    handleTransfer(row) {
      let ids
      if (row && row.id) {
        ids = [row.id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      this.transfer.show = true
      this.transfer.ids = ids
    },
    // 编辑列表
    handleEdit(row) {
      this.showDrawer = true
      Object.assign(this.baseInfo, row)
      this.parentname = row.department && row.department.name
      this.baseInfo.role_id = row.roles.map(item => item.id)
      this.baseInfo.password = undefined
    },
    // 删除列表
    // handleRmove(row) {
    //   let ids = []
    //   if (row) {
    //     ids = [row.id]
    //   } else {
    //     ids = this.multipleSelection.map(item => item.id)
    //   }
    //   this.$confirm(this.$t('tips.delete'), this.$t('other.tip'), {
    //     center: true,
    //     type: 'warning'
    //   }).then(() => {
    //     deleteRole({id: [row.id]}).then(() => {
    //       this.$message.success('success')
    //       this.getList()
    //     })
    //   })
    // },
    // 批量设置状态
    setStatusAll(status) {
      let ids = this.multipleSelection.map(item => item.id)
      this.updateStatus({id: ids, status})
    },
    // 设置状态
    setStatus(row) {
      let status = row.status == 1 ? 2 : 1
      this.updateStatus({id: [row.id], status})
    },
    // 更新状态
    updateStatus(params) {
      setStatus(params).then(() => {
        this.$message.success('success')
        this.getList()
      })
    },
    // 右侧窗口关闭事件
    handleCancel() {
      this.resetForm()
    },
    // 重置表达数据和验证
    resetForm () {
      Object.assign(this.baseInfo, this._baseInfo)
      this.parentname = ''
      this.$refs.form.resetValidation()
    },
    // 右侧窗口确定事件
    handleOk() {
      // console.log(this.baseInfo)
      if(this.$refs.form.validate()) {
        if(this.baseInfo.id) {
          updateUser(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList()
            this.showDrawer = false
          })
        } else {
          createUser(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList(1)
            this.showDrawer = false
          })
        }
      }
    }
  }
}
</script>
